using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Linq;
using ERP_SaaS_WinForm.生产工单_报工_工序.Process;
using CCWin;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Text;

namespace ERP_SaaS_WinForm.生产工单_报工_工序
{
    public class ScheduleForm : CCSkinMain
    {
        private readonly ProductionOrders source;
        private TabControl tabControl;
        private Panel panelSchedule;
        private Panel panelProcessFlow;
        
        // 排产信息控件
        private TextBox txtPlannedQuantity;
        private DateTimePicker dtpPlanStart;
        private DateTimePicker dtpPlanEnd;
        private DateTimePicker dtpDemandDate;
        private TextBox txtRemark;
        private Button btnOk;
        private Button btnCancel;
        
        // 工序流程控件
        private Panel panelProcessSteps;
        private DataGridView dgvProcessTasks;
        private Button btnAddProcess;
        private Button btnEditProcess;
        
        private Button btnSaveProcess;
        
        // 数据
        private List<ProcessTable>[] stepProcesses;
        private List<ProcessTable> allProcesses;
        private List<ProductionProcessTable> existingProcessData;
        private int currentProcessStep = 1;
        private bool isReadOnly = false; // 添加只读模式标志
        
        public ScheduleForm(ProductionOrders orders)
        {
            source = orders ?? new ProductionOrders();
            stepProcesses = new List<ProcessTable>[4];
            for (int i = 0; i < stepProcesses.Length; i++) stepProcesses[i] = new List<ProcessTable>();
            allProcesses = new List<ProcessTable>();
            existingProcessData = new List<ProductionProcessTable>();
            isReadOnly = false;
            InitializeForm();
        }
        
        public ScheduleForm(ProductionOrders orders, bool readOnly)
        {
            source = orders ?? new ProductionOrders();
            stepProcesses = new List<ProcessTable>[4];
            for (int i = 0; i < stepProcesses.Length; i++) stepProcesses[i] = new List<ProcessTable>();
            allProcesses = new List<ProcessTable>();
            existingProcessData = new List<ProductionProcessTable>();
            isReadOnly = readOnly;
            InitializeForm();
        }

        // 任务表格状态显示：0=启用、1=禁用，并用颜色强化提示
        private void OnTasksCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex < 0) return;
            var grid = sender as DataGridView;
            if (grid?.Columns[e.ColumnIndex].Name != "State" || e.Value == null) return;
            int v; if (!int.TryParse(e.Value.ToString(), out v)) return;
            e.Value = (v == 0 ? "启用" : "禁用");
            e.FormattingApplied = true;
            var row = grid.Rows[e.RowIndex];
            row.DefaultCellStyle.ForeColor = (v == 0 ? Color.FromArgb(34, 139, 34) : Color.FromArgb(178, 34, 34));
        }

        // 对话框表格状态显示：0=启用、1=禁用，并用颜色强化提示
        private void OnDialogCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex < 0) return;
            var grid = sender as DataGridView;
            if (grid?.Columns[e.ColumnIndex].Name != "State" || e.Value == null) return;
            int v; if (!int.TryParse(e.Value.ToString(), out v)) return;
            e.Value = (v == 0 ? "启用" : "禁用");
            e.FormattingApplied = true;
            var row = grid.Rows[e.RowIndex];
            row.DefaultCellStyle.ForeColor = (v == 0 ? Color.FromArgb(34, 139, 34) : Color.FromArgb(178, 34, 34));
        }

        private void InitializeForm()
        {
            Text = isReadOnly ? "生产工单查看" : "生产工单排产";
            StartPosition = FormStartPosition.CenterParent;
            Size = new Size(1000, 700);
            MinimizeBox = false;
            MaximizeBox = false;
            FormBorderStyle = FormBorderStyle.FixedDialog;

            // 创建标签页控件
            tabControl = new TabControl
            {
                Dock = DockStyle.Fill
            };

            // 创建排产信息标签页
            var tabSchedule = new TabPage("排产信息");
            panelSchedule = CreateSchedulePanel();
            tabSchedule.Controls.Add(panelSchedule);

            // 创建工序流程标签页
            var tabProcessFlow = new TabPage("工序流程");
            panelProcessFlow = CreateProcessFlowPanel();
            tabProcessFlow.Controls.Add(panelProcessFlow);

            // 创建物料清单标签页
            var tabMaterialList = new TabPage("物料清单");
            var panelMaterialList = CreateMaterialListPanel();
            tabMaterialList.Controls.Add(panelMaterialList);

            tabControl.TabPages.Add(tabSchedule);
            tabControl.TabPages.Add(tabProcessFlow);
            tabControl.TabPages.Add(tabMaterialList);

            Controls.Add(tabControl);

            // 加载数据
            _ = LoadProcessData();
            _ = LoadExistingProcessData();
        }

        private Panel CreateSchedulePanel()
        {
            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(20) };

            // 工单信息显示（基础信息分组 + 表格）
            var infoTable = CreateInfoTable();
            var gbInfo = new GroupBox
            {
                Text = "基础信息",
                Location = new Point(20, 20),
                Size = new Size(940, 210)
            };
            infoTable.Dock = DockStyle.Fill;
            gbInfo.Controls.Add(infoTable);

            // 输入区域从基础信息分组下方开始
            int inputTop = 20 + gbInfo.Height + 15;
            var lblRequired1 = new Label { Text = "*", ForeColor = Color.Red, Location = new Point(10, inputTop + 2), AutoSize = true };

            // 计划数量
            var lblQuantity = new Label { Text = "计划数量:", Location = new Point(20, inputTop), AutoSize = true };
            txtPlannedQuantity = new TextBox
            {
                Location = new Point(120, inputTop - 3),
                Size = new Size(200, 25),
                Text = source.PlannedQuantity > 0 ? source.PlannedQuantity.ToString() : "",
                ReadOnly = isReadOnly
            };

            // 计划开始时间
            var lblRequired2 = new Label { Text = "*", ForeColor = Color.Red, Location = new Point(10, inputTop + 42), AutoSize = true };
            var lblStart = new Label { Text = "计划开工时间:", Location = new Point(20, inputTop + 40), AutoSize = true };
            dtpPlanStart = new DateTimePicker
            {
                Location = new Point(120, inputTop + 37),
                Size = new Size(200, 25),
                Format = DateTimePickerFormat.Custom,
                CustomFormat = "yyyy-MM-dd HH:mm",
                Enabled = !isReadOnly
            };

            // 计划结束时间
            var lblRequired3 = new Label { Text = "*", ForeColor = Color.Red, Location = new Point(10, inputTop + 82), AutoSize = true };
            var lblEnd = new Label { Text = "计划完工时间:", Location = new Point(20, inputTop + 80), AutoSize = true };
            dtpPlanEnd = new DateTimePicker
            {
                Location = new Point(120, inputTop + 77),
                Size = new Size(200, 25),
                Format = DateTimePickerFormat.Custom,
                CustomFormat = "yyyy-MM-dd HH:mm",
                Enabled = !isReadOnly
            };

            // 需求日期
            var lblDemand = new Label { Text = "需求日期:", Location = new Point(20, inputTop + 120), AutoSize = true };
            dtpDemandDate = new DateTimePicker
            {
                Location = new Point(120, inputTop + 117),
                Size = new Size(200, 25),
                Format = DateTimePickerFormat.Custom,
                CustomFormat = "yyyy-MM-dd HH:mm",
                Enabled = !isReadOnly
            };

            // 备注
            var lblRemark = new Label { Text = "备注:", Location = new Point(20, inputTop + 160), AutoSize = true };
            txtRemark = new TextBox
            {
                Location = new Point(120, inputTop + 157),
                Size = new Size(400, 60),
                Multiline = true,
                Text = source.Remark ?? "",
                ReadOnly = isReadOnly
            };

            // 按钮
            btnOk = new Button
            {
                Text = "确定排产并提交",
                Location = new Point(120, inputTop + 230),
                Size = new Size(120, 35),
                BackColor = Color.LightBlue,
                Visible = !isReadOnly
            };
            btnOk.Click += BtnOk_Click;

            btnCancel = new Button
            {
                Text = isReadOnly ? "关闭" : "取消",
                Location = new Point(260, inputTop + 230),
                Size = new Size(80, 35)
            };
            btnCancel.Click += (s, e) => { DialogResult = DialogResult.Cancel; Close(); };

            // 预填可用的时间字段
            if (source.PlanStart > DateTime.MinValue) dtpPlanStart.Value = source.PlanStart;
            if (source.PlanEnd > DateTime.MinValue) dtpPlanEnd.Value = source.PlanEnd;
            if (source.DemandDate > DateTime.MinValue) dtpDemandDate.Value = source.DemandDate;

            panel.Controls.AddRange(new Control[]
            {
                gbInfo,
                lblRequired1, lblQuantity, txtPlannedQuantity,
                lblRequired2, lblStart, dtpPlanStart,
                lblRequired3, lblEnd, dtpPlanEnd,
                lblDemand, dtpDemandDate, lblRemark, txtRemark,
                btnOk, btnCancel
            });

            return panel;
        }

        private string GetOrderInfoText()
        {
            string Safe(object v) => v == null ? "-" : v.ToString();
            string FormatDate(DateTime dt) => dt > DateTime.MinValue ? dt.ToString("yyyy-MM-dd HH:mm") : "-";

            return string.Join("\n", new string[]
            {
                $"工单编号: {Safe(source.ProductionOrdersCode)}",
                $"工单名称: {Safe(source.ProductionOrdersName)}",
                $"产品名称: {Safe(source.ProductName)}",
                $"计划编号: {Safe(source.PlanNumber)}",
                $"产品编号: {Safe(source.ProductCode)}",
                $"规格型号: {Safe(source.SpecificationModel)}",
                $"单位: {Safe(source.Unit)}",
                $"产品类型: {Safe(source.ProductType)}  版本: {Safe(source.Version)}",
                $"计划数量: {(source.PlannedQuantity > 0 ? source.PlannedQuantity.ToString() : "-")}  实际数量: {(source.ActualQuantity > 0 ? source.ActualQuantity.ToString() : "-")}",
                $"计划开工: {FormatDate(source.PlanStart)}  计划完工: {FormatDate(source.PlanEnd)}",
                $"实际开工: {FormatDate(source.ActualStart)}  实际完工: {FormatDate(source.ActualEnd)}",
                $"生产批次: {Safe(source.Batch)}  需求日期: {FormatDate(source.DemandDate)}"
            });
        }

        private TableLayoutPanel CreateInfoTable()
        {
            string V(object v) => v == null ? "-" : v.ToString();

            var table = new TableLayoutPanel
            {
                Location = new Point(20, 20),
                Size = new Size(920, 180),
                ColumnCount = 4,
                RowCount = 6,
                AutoSize = false
            };
            table.ColumnStyles.Clear();
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 90));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 330));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 90));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));

            for (int i = 0; i < 6; i++)
                table.RowStyles.Add(new RowStyle(SizeType.Absolute, 28));

            Label L(string t) => new Label
            {
                Text = t,
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleLeft,
                Dock = DockStyle.Fill,
                ForeColor = Color.DimGray,
                Font = new Font("Microsoft YaHei", 9, FontStyle.Regular),
                Padding = new Padding(0, 6, 0, 0)
            };
            Label VLabel(string t) => new Label
            {
                Text = string.IsNullOrWhiteSpace(t) ? "-" : t,
                AutoSize = true,
                ForeColor = Color.Black,
                Dock = DockStyle.Fill,
                Font = new Font("Microsoft YaHei", 10, FontStyle.Regular),
                Padding = new Padding(0, 6, 0, 0)
            };

            int r = 0;
            table.Controls.Add(L("工单编号"), 0, r); table.Controls.Add(VLabel(V(source.ProductionOrdersCode)), 1, r);
            table.Controls.Add(L("工单名称"), 2, r); table.Controls.Add(VLabel(V(source.ProductionOrdersName)), 3, r++);
            table.Controls.Add(L("关联计划"), 0, r); table.Controls.Add(VLabel(V(source.AssociatePlans)), 1, r);
            table.Controls.Add(L("计划编号"), 2, r); table.Controls.Add(VLabel(V(source.PlanNumber)), 3, r++);
            table.Controls.Add(L("类型"), 0, r); table.Controls.Add(VLabel(V(source.Type)), 1, r);
            table.Controls.Add(L("产品名称"), 2, r); table.Controls.Add(VLabel(V(source.ProductName)), 3, r++);
            table.Controls.Add(L("产品编号"), 0, r); table.Controls.Add(VLabel(V(source.ProductCode)), 1, r);
            table.Controls.Add(L("规格型号"), 2, r); table.Controls.Add(VLabel(V(source.SpecificationModel)), 3, r++);
            table.Controls.Add(L("产品类型"), 0, r); table.Controls.Add(VLabel(V(source.ProductType)), 1, r);
            table.Controls.Add(L("单位"), 2, r); table.Controls.Add(VLabel(V(source.Unit)), 3, r++);
            table.Controls.Add(L("BOM"), 0, r); table.Controls.Add(VLabel(V(source.BOM)), 1, r);
            table.Controls.Add(L("版本"), 2, r); table.Controls.Add(VLabel(V(source.Version)), 3, r++);

            return table;
        }

        private Panel CreateProcessFlowPanel()
        {
            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(20) };

            // 工序步骤导航
            panelProcessSteps = new Panel
            {
                Location = new Point(20, 20),
                Size = new Size(800, 80),
                BackColor = Color.WhiteSmoke
            };
            CreateProcessSteps();

            // 工序任务表格
            dgvProcessTasks = new DataGridView
            {
                Location = new Point(20, 120),
                Size = new Size(800, 300),
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = isReadOnly,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                BackgroundColor = Color.White,
                RowHeadersVisible = false,
                ScrollBars = ScrollBars.Both,
                EditMode = isReadOnly ? DataGridViewEditMode.EditProgrammatically : DataGridViewEditMode.EditOnEnter
            };

            // 操作按钮
            btnAddProcess = new Button
            {
                Text = "新增",
                Location = new Point(20, 440),
                Size = new Size(80, 30),
                BackColor = Color.LightGreen,
                Visible = !isReadOnly
            };
            btnAddProcess.Click += BtnAddProcess_Click;

            btnEditProcess = new Button
            {
                Text = "编辑",
                Location = new Point(120, 440),
                Size = new Size(80, 30),
                BackColor = Color.LightYellow,
                Visible = !isReadOnly
            };
            btnEditProcess.Click += BtnEditProcess_Click;

            btnSaveProcess = new Button
            {
                Text = "保存",
                Location = new Point(220, 440),
                Size = new Size(80, 30),
                Visible = !isReadOnly
            };
            btnSaveProcess.Click += BtnSaveProcess_Click;

            panel.Controls.AddRange(new Control[]
            {
                panelProcessSteps, dgvProcessTasks, btnAddProcess, btnEditProcess, btnSaveProcess
            });

            return panel;
        }

        private void CreateProcessSteps()
        {
            panelProcessSteps.Controls.Clear();
            string[] stepNames = { "工序一", "工序二", "工序三", "工序四" };

            for (int i = 0; i < 4; i++)
            {
                int stepIndex = i + 1;
                var stepPanel = new Panel
                {
                    Location = new Point(20 + i * 180, 20),
                    Size = new Size(160, 40),
                    BackColor = stepIndex == currentProcessStep ? Color.LightBlue : Color.White,
                    BorderStyle = BorderStyle.FixedSingle
                };

                var stepNumber = new Label
                {
                    Text = stepNames[i],
                    Location = new Point(5, 5),
                    AutoSize = true,
                    Font = new Font("Microsoft YaHei", 10, FontStyle.Bold)
                };

                string SummaryName(List<ProcessTable> list)
                {
                    if (list == null || list.Count == 0) return "未选择";
                    var first = list[0]?.ProcessName ?? "";
                    return list.Count == 1 ? first : $"{first} 等{list.Count}项";
                }

                var stepName = new Label
                {
                    Text = SummaryName(stepProcesses[i]),
                    Location = new Point(5, 25),
                    AutoSize = true,
                    Font = new Font("Microsoft YaHei", 8),
                    ForeColor = Color.Gray
                };

                stepPanel.Controls.Add(stepNumber);
                stepPanel.Controls.Add(stepName);

                // 绑定点击事件
                stepPanel.Click += (s, e) => SelectProcessStep(stepIndex);
                stepNumber.Click += (s, e) => SelectProcessStep(stepIndex);
                stepName.Click += (s, e) => SelectProcessStep(stepIndex);

                // 绘制边框
                stepPanel.Paint += (s, e) =>
                {
                    if (stepIndex == currentProcessStep)
                    {
                        using (var pen = new Pen(Color.Blue, 2))
                        {
                            e.Graphics.DrawRectangle(pen, 0, 0, stepPanel.Width - 1, stepPanel.Height - 1);
                        }
                    }
                };

                panelProcessSteps.Controls.Add(stepPanel);
            }
        }

        private void SelectProcessStep(int stepIndex)
        {
            currentProcessStep = stepIndex;
            UpdateProcessStepSelection(stepIndex);
            ShowProcessFlowInfo();
        }

        private void UpdateProcessStepSelection(int selectedStep)
        {
            for (int i = 0; i < panelProcessSteps.Controls.Count; i++)
            {
                var panel = panelProcessSteps.Controls[i] as Panel;
                if (panel != null)
                {
                    panel.BackColor = (i + 1) == selectedStep ? Color.LightBlue : Color.White;
                    panel.Invalidate(); // 重绘边框
                }
            }
        }

        private void ShowProcessFlowInfo()
        {
            dgvProcessTasks.DataSource = null;
            dgvProcessTasks.Columns.Clear();

            // 设置列（首列复选框 + 备注）
            var chk = new DataGridViewCheckBoxColumn
            {
                Name = "Selected",
                HeaderText = "选择",
                Width = 50
            };
            dgvProcessTasks.Columns.Add(chk);
            dgvProcessTasks.Columns.Add("ProcessId", "工序ID");
            dgvProcessTasks.Columns.Add("ProcessCode", "工序编号");
            dgvProcessTasks.Columns.Add("ProcessName", "工序名称");
            dgvProcessTasks.Columns.Add("ProcessDescription", "工序说明");
            dgvProcessTasks.Columns.Add("State", "状态");
            dgvProcessTasks.Columns.Add("Remark", "备注");
            // 样式优化
            dgvProcessTasks.EnableHeadersVisualStyles = false;
            dgvProcessTasks.ColumnHeadersDefaultCellStyle.BackColor = Color.WhiteSmoke;
            dgvProcessTasks.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvProcessTasks.Columns["State"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvProcessTasks.Columns["Selected"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            // 显示状态：0=启用，1=禁用（带颜色）
            dgvProcessTasks.CellFormatting -= OnTasksCellFormatting;
            dgvProcessTasks.CellFormatting += OnTasksCellFormatting;

            // 显示当前步骤已选的工序信息
            var selectedList = stepProcesses[currentProcessStep - 1];
            foreach (var currentProcess in selectedList)
            {
                dgvProcessTasks.Rows.Add(
                    true,
                    currentProcess.ProcessId,
                    currentProcess.ProcessCode,
                    currentProcess.ProcessName,
                    currentProcess.ProcessDescription,
                    currentProcess.State,
                    currentProcess.Remark
                );
            }

            // 仅显示当前步骤已选择的工序
        }

        private async void BtnAddProcess_Click(object sender, EventArgs e)
        {
            if (allProcesses.Count == 0)
            {
                MessageBox.Show("正在加载工序数据，请稍候...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            using (var dlg = new AddProcessForm(allProcesses, stepProcesses[currentProcessStep - 1]))
            {
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    AddProcessesToFlow(dlg.SelectedProcesses);
                    ShowProcessFlowInfo();
                }
            }
        }

        private void AddProcessesToFlow(List<ProcessTable> processes)
        {
            if (processes == null || processes.Count == 0) return;
            var list = stepProcesses[currentProcessStep - 1];
            foreach (var p in processes)
            {
                if (!list.Any(x => x.ProcessId == p.ProcessId))
                {
                    list.Add(p);
                }
            }
        }

        // 将当前步骤的工序完全替换为传入集合（去重并保持顺序）
        private void ReplaceProcessesForCurrentStep(List<ProcessTable> processes)
        {
            var result = new List<ProcessTable>();
            var seen = new HashSet<int>();
            if (processes != null)
            {
                foreach (var p in processes)
                {
                    if (p == null) continue;
                    if (seen.Add(p.ProcessId)) result.Add(p);
                }
            }
            stepProcesses[currentProcessStep - 1] = result;
        }

        private void BtnEditProcess_Click(object sender, EventArgs e)
        {
            using (var dlg = new AddProcessForm(allProcesses, stepProcesses[currentProcessStep - 1]))
            {
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    // 编辑采用覆盖语义：结果必须与勾选一致
                    ReplaceProcessesForCurrentStep(dlg.SelectedProcesses);
                    ShowProcessFlowInfo();
                }
            }
        }

        // 删除功能已取消

        private async Task LoadProcessData()
        {
            try
            {
                await Task.Delay(100); // 确保UI已准备好
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    var response = await httpClient.GetAsync("http://localhost:5257/api/ProductionOrders/ProcessTableCommand");
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<SimpleApiResponse<List<ProcessTable>>>(json);
                    allProcesses = apiResponse?.data ?? new List<ProcessTable>();

                    Console.WriteLine($"加载工序数据成功，共 {allProcesses.Count} 条");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载工序数据失败: {ex.Message}");
                MessageBox.Show($"加载工序数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadExistingProcessData()
        {
            try
            {
                await Task.Delay(200); // 确保UI已准备好
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    
                    // 加载每个步骤的工序数据
                    for (int processNumber = 1; processNumber <= 4; processNumber++)
                    {
                        var requestUrl = $"http://localhost:5257/api/ProductionProcess/ProductionProcessTableCommand?ProductionOrdersId={source.ProductionOrdersId}&ProcessNumber={processNumber}";
                        var response = await httpClient.GetAsync(requestUrl);
                        
                        if (response.IsSuccessStatusCode)
                        {
                            var json = await response.Content.ReadAsStringAsync();
                            var apiResponse = JsonConvert.DeserializeObject<SimpleApiResponse<List<ProductionProcessTable>>>(json);
                            var stepData = apiResponse?.data ?? new List<ProductionProcessTable>();
                            
                            existingProcessData.AddRange(stepData);
                            
                            // 如果找到数据，更新当前步骤的已选工序列表
                            if (stepData.Count > 0)
                            {
                                var list = stepProcesses[processNumber - 1];
                                foreach (var processData in stepData)
                                {
                                    if (!list.Any(x => x.ProcessId == processData.ProcessId))
                                    {
                                        list.Add(new ProcessTable
                                        {
                                            ProcessId = processData.ProcessId,
                                            ProcessCode = processData.ProcessCode,
                                            ProcessName = processData.ProcessName,
                                            ProcessDescription = processData.ProcessDescription,
                                            State = processData.State,
                                            Remark = processData.Remark
                                        });
                                    }
                                }
                            }
                        }
                    }

                    Console.WriteLine($"加载现有工序数据成功，共 {existingProcessData.Count} 条");
                    
                    // 更新UI
                    this.Invoke(new Action(() =>
                    {
                        CreateProcessSteps();
                        ShowProcessFlowInfo();
                    }));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载现有工序数据失败: {ex.Message}");
            }
        }

        private async void BtnOk_Click(object sender, EventArgs e)
        {
            await SaveAllAsync();
        }

        private async void BtnSaveProcess_Click(object sender, EventArgs e)
        {
            await SaveAllAsync();
        }

        private async Task SaveAllAsync()
        {
            try
            {
                // 验证日期
                if (dtpPlanEnd.Value <= dtpPlanStart.Value)
                {
                    MessageBox.Show("计划结束时间必须晚于计划开始时间", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (dtpDemandDate.Value <= dtpPlanEnd.Value)
                {
                    MessageBox.Show("需求日期必须晚于计划结束时间", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证数量
                if (!int.TryParse(txtPlannedQuantity.Text, out int quantity) || quantity <= 0)
                {
                    MessageBox.Show("请输入有效的计划数量", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    // 提交排产信息
                    var scheduleCommand = new ProductionOrdersHandleCommand
                    {
                        ProductionOrdersId = source.ProductionOrdersId,
                        PlannedQuantity = quantity,
                        PlanStart = dtpPlanStart.Value.ToString("yyyy-MM-ddTHH:mm:ss"),
                        PlanEnd = dtpPlanEnd.Value.ToString("yyyy-MM-ddTHH:mm:ss"),
                        DemandDate = dtpDemandDate.Value.ToString("yyyy-MM-ddTHH:mm:ss"),
                        Remark = txtRemark.Text,
                        ActualStart = dtpPlanStart.Value.ToString("yyyy-MM-ddTHH:mm:ss"),
                        ActualEnd = dtpPlanEnd.Value.ToString("yyyy-MM-ddTHH:mm:ss"),

                        // 以下为后端校验要求的字段，从所选工单补齐
                        ProductionOrdersCode = source.ProductionOrdersCode,
                        ProductionOrdersName = source.ProductionOrdersName,
                        AssociatePlans = source.AssociatePlans,
                        PlanNumber = source.PlanNumber,
                        Type = source.Type,
                        ProductName = source.ProductName,
                        ProductCode = source.ProductCode,
                        SpecificationModel = source.SpecificationModel,
                        Unit = source.Unit,
                        ProductType = source.ProductType,
                        BOM = source.BOM,
                        Version = source.Version,
                        Batch = string.IsNullOrWhiteSpace(source.Batch) ? $"{DateTime.Now:yyyyMMddHHmmss}" : source.Batch,
                        CreateBy = Environment.UserName,
                        // 更新状态：排产后状态变为"未开始"
                        State = 1
                    };

                    var scheduleJson = JsonConvert.SerializeObject(scheduleCommand);
                    var scheduleContent = new StringContent(scheduleJson, Encoding.UTF8, "application/json");
                    
                    Console.WriteLine($"提交排产数据: {scheduleJson}");
                    var scheduleResponse = await httpClient.PostAsync("http://localhost:5257/api/ProductionOrders/Handle", scheduleContent);
                    
                    if (!scheduleResponse.IsSuccessStatusCode)
                    {
                        var errorContent = await scheduleResponse.Content.ReadAsStringAsync();
                        MessageBox.Show($"排产提交失败: {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    // 提交工序流程
                    await SubmitProcessFlow(httpClient);

                    MessageBox.Show("排产和工序流程提交成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 提示后关闭窗口并让父窗体刷新（从而看到状态变化）
                    try { source.State = 1; } catch { }
                    // 确保状态更新被保存
                    source.State = 1;
                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"提交失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task SubmitProcessFlow(HttpClient httpClient)
        {
            try
            {
                // 根据 Swagger：/api/ProductionProcess/UpdProductionProcessTableCommand
                // 请求体示例：{ "productionOrdersId": 6, "processNumber": 2, "processIds": [6,5] }
                for (int i = 0; i < stepProcesses.Length; i++)
                {
                    var processIds = stepProcesses[i]
                        .Select(p => p?.ProcessId ?? 0)
                        .Where(id => id > 0)
                        .Distinct()
                        .ToArray();

                    // 若该步骤没有选择任何工序，可按需跳过或清空。这里：为空就跳过不提交
                    if (processIds.Length == 0) continue;

                    var requestBody = new
                    {
                        productionOrdersId = source.ProductionOrdersId,
                        processNumber = i + 1,
                        processIds = processIds
                    };

                    var json = JsonConvert.SerializeObject(requestBody);
                    Console.WriteLine($"提交工序更新 Step={i + 1}: {json}");
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    var resp = await httpClient.PostAsync("http://localhost:5257/api/ProductionProcess/UpdProductionProcessTableCommand", content);
                    var txt = await resp.Content.ReadAsStringAsync();
                    if (!resp.IsSuccessStatusCode)
                    {
                        throw new Exception($"步骤 {i + 1} 更新失败: {txt}");
                    }

                    var api = JsonConvert.DeserializeObject<SimpleApiResponse<int>>(txt);
                    if (api == null || api.code != 200)
                    {
                        throw new Exception($"步骤 {i + 1} 更新失败: {api?.message ?? txt}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"提交工序流程异常: {ex.Message}");
                throw;
            }
        }

        // 工序选择对话框
        private class AddProcessForm : Form
        {
            private DataGridView dgvProcesses;
            private Button btnSelect;
            private Button btnCancel;
            public List<ProcessTable> SelectedProcesses { get; private set; }
            private readonly HashSet<int> preselectedIds;

            public AddProcessForm(List<ProcessTable> processes)
            {
                SelectedProcesses = new List<ProcessTable>();
                preselectedIds = new HashSet<int>();
                InitializeForm(processes);
            }

            public AddProcessForm(List<ProcessTable> processes, IEnumerable<ProcessTable> selected)
            {
                SelectedProcesses = new List<ProcessTable>();
                preselectedIds = new HashSet<int>((selected ?? Enumerable.Empty<ProcessTable>()).Select(x => x.ProcessId));
                InitializeForm(processes);
            }

            private void InitializeForm(List<ProcessTable> processes)
            {
                Text = "选择工序";
                StartPosition = FormStartPosition.CenterParent;
                Size = new Size(600, 500);
                FormBorderStyle = FormBorderStyle.FixedDialog;
                MaximizeBox = false;
                MinimizeBox = false;

                // 说明标签
                var lblInstruction = new Label
                {
                    Text = "点击行选择工序，支持多选",
                    Location = new Point(20, 20),
                    AutoSize = true,
                    Font = new Font("Microsoft YaHei", 9)
                };

                // 工序表格
                dgvProcesses = new DataGridView
                {
                    Location = new Point(20, 50),
                    Size = new Size(540, 300),
                    AllowUserToAddRows = false,
                    AllowUserToDeleteRows = false,
                    ReadOnly = false,
                    SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                    MultiSelect = false,
                    BackgroundColor = Color.White,
                    RowHeadersVisible = false,
                    EditMode = DataGridViewEditMode.EditOnEnter
                };
                // 勾选即时提交，避免未提交导致读取到旧值
                dgvProcesses.CurrentCellDirtyStateChanged += (s, e) =>
                {
                    if (dgvProcesses.IsCurrentCellDirty)
                    {
                        dgvProcesses.CommitEdit(DataGridViewDataErrorContexts.Commit);
                    }
                };

                // 设置列（首列复选框 + 备注）
                var chk = new DataGridViewCheckBoxColumn { Name = "Selected", HeaderText = "选择", Width = 55 };
                dgvProcesses.Columns.Add(chk);
                dgvProcesses.Columns.Add("ProcessId", "工序ID");
                dgvProcesses.Columns.Add("ProcessCode", "工序编号");
                dgvProcesses.Columns.Add("ProcessName", "工序名称");
                dgvProcesses.Columns.Add("ProcessDescription", "工序说明");
                dgvProcesses.Columns.Add("State", "状态");
                dgvProcesses.Columns.Add("Remark", "备注");
                foreach (DataGridViewColumn c in dgvProcesses.Columns)
                {
                    if (c.Name != "Selected") c.ReadOnly = true;
                }
                // 样式优化
                dgvProcesses.EnableHeadersVisualStyles = false;
                dgvProcesses.ColumnHeadersDefaultCellStyle.BackColor = Color.WhiteSmoke;
                dgvProcesses.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgvProcesses.Columns["State"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgvProcesses.Columns["Selected"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

                // 显示状态：0=启用，1=禁用（带颜色）
                dgvProcesses.CellFormatting -= OnDialogCellFormatting;
                dgvProcesses.CellFormatting += OnDialogCellFormatting;

                // 绑定数据
                foreach (var process in processes)
                {
                    bool isSelected = false;
                    try { isSelected = preselectedIds != null && preselectedIds.Contains(process.ProcessId); } catch { }
                    dgvProcesses.Rows.Add(
                        isSelected,
                        process.ProcessId,
                        process.ProcessCode,
                        process.ProcessName,
                        process.ProcessDescription,
                        process.State,
                        process.Remark
                    );
                }

                // 按钮
                btnSelect = new Button
                {
                    Text = "确定选择",
                    Location = new Point(400, 370),
                    Size = new Size(80, 30),
                    BackColor = Color.LightBlue
                };
                btnSelect.Click += BtnSelect_Click;

                btnCancel = new Button
                {
                    Text = "取消",
                    Location = new Point(490, 370),
                    Size = new Size(80, 30)
                };
                btnCancel.Click += (s, e) => { DialogResult = DialogResult.Cancel; Close(); };

                // 绑定点击事件
                dgvProcesses.CellClick += DgvProcesses_CellClick;

                Controls.AddRange(new Control[]
                {
                    lblInstruction, dgvProcesses, btnSelect, btnCancel
                });
            }

            // 对话框内部的状态格式化（0=启用、1=禁用 + 颜色）
            private void OnDialogCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                if (e.ColumnIndex < 0) return;
                var grid = sender as DataGridView;
                if (grid?.Columns[e.ColumnIndex].Name != "State" || e.Value == null) return;
                int v; if (!int.TryParse(e.Value.ToString(), out v)) return;
                e.Value = (v == 0 ? "启用" : "禁用");
                e.FormattingApplied = true;
                var row = grid.Rows[e.RowIndex];
                row.DefaultCellStyle.ForeColor = (v == 0 ? Color.FromArgb(34, 139, 34) : Color.FromArgb(178, 34, 34));
            }

            private void DgvProcesses_CellClick(object sender, DataGridViewCellEventArgs e)
            {
                if (e.RowIndex >= 0)
                {
                    dgvProcesses.Rows[e.RowIndex].Selected = !dgvProcesses.Rows[e.RowIndex].Selected;
                }
            }

            private void BtnSelect_Click(object sender, EventArgs e)
            {
                // 提交当前编辑中的复选框值
                try { dgvProcesses.EndEdit(); } catch { }
                SelectedProcesses.Clear();
                foreach (DataGridViewRow row in dgvProcesses.Rows)
                {
                    if (row == null) continue;
                    var selected = false;
                    if (dgvProcesses.Columns.Contains("Selected"))
                    {
                        var idx = dgvProcesses.Columns["Selected"].Index;
                        var cell = row.Cells[idx];
                        bool.TryParse(Convert.ToString(cell?.Value), out selected);
                    }
                    if (!selected) continue;

                    ProcessTable process = null;
                    try
                    {
                        int id = 0; int.TryParse(row.Cells["ProcessId"]?.Value?.ToString(), out id);
                        int state = 0; int.TryParse(row.Cells["State"]?.Value?.ToString(), out state);
                        process = new ProcessTable
                        {
                            ProcessId = id,
                            ProcessCode = row.Cells["ProcessCode"]?.Value?.ToString(),
                            ProcessName = row.Cells["ProcessName"]?.Value?.ToString(),
                            ProcessDescription = row.Cells["ProcessDescription"]?.Value?.ToString(),
                            State = state,
                            Remark = row.Cells["Remark"]?.Value?.ToString() ?? string.Empty
                        };
                    }
                    catch { /* ignore row parse errors */ }

                    if (process != null)
                    {
                        SelectedProcesses.Add(process);
                    }
                }

                if (SelectedProcesses.Count == 0)
                {
                    MessageBox.Show("请至少选择一个工序", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private Panel CreateMaterialListPanel()
        {
            var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(20) };

            // 标题
            var lblTitle = new Label
            {
                Text = "物料清单",
                Font = new Font("微软雅黑", 16, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(20, 20),
                Size = new Size(200, 30),
                TextAlign = ContentAlignment.MiddleLeft
            };

            // 查看物料清单按钮
            var btnViewMaterials = new Button
            {
                Text = "查看物料清单",
                Location = new Point(20, 70),
                Size = new Size(150, 40),
                BackColor = Color.FromArgb(70, 130, 180),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                FlatStyle = FlatStyle.Flat
            };
            btnViewMaterials.FlatAppearance.BorderSize = 0;
            btnViewMaterials.Click += BtnViewMaterials_Click;

            // 说明文字
            var lblDescription = new Label
            {
                Text = "点击按钮查看该生产工单的物料清单信息",
                Font = new Font("微软雅黑", 10),
                ForeColor = Color.FromArgb(100, 100, 100),
                Location = new Point(20, 130),
                Size = new Size(400, 25),
                TextAlign = ContentAlignment.MiddleLeft
            };

            panel.Controls.AddRange(new Control[]
            {
                lblTitle,
                btnViewMaterials,
                lblDescription
            });

            return panel;
        }

        private void BtnViewMaterials_Click(object sender, EventArgs e)
        {
            try
            {
                var materialForm = new MaterialListForm(source.ProductionOrdersId, isReadOnly);
                materialForm.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开物料清单时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScheduleForm));
            this.SuspendLayout();
            // 
            // ScheduleForm
            // 
            this.ClientSize = new System.Drawing.Size(1392, 846);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "ScheduleForm";
            this.ResumeLayout(false);

        }
    }
}
